//
//  NewsViewController.m
//  新写项目
//
//  Created by 安松林的dlios on 14-12-31.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsCollectionViewCell.h"
#import "ConnectModel.h"
#import "NewsModel.h"
#import "SortModel.h"
#import "DetailViewController.h"
#import "OneItemCollectionViewCell.h"
#import "HeaderViewController.h"

@interface NewsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,NewsCollectionViewCellDelegate,OneItemCollectionViewCellDelegate>

@end

@implementation NewsViewController
- (void)dealloc
{
    [_button release];
    [_buttonArray release];
    [_collection release];
    [_headerArray release];
    [_collectionArray release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectionArray = [NSMutableArray array];
        self.buttonArray = [NSMutableArray array];
        self.headerArray = [NSMutableArray array];
       
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    // Do any additional setup after loading the view.
   
    [self createVC];
//    [self createAnimation];
    [self createData];
}
//- (void)createAnimation
//{
//    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//    UIImage *image = [UIImage imageNamed:@"0.jpg"];
//    imageView.image = image;
//    [self.view addSubview:imageView];
//    [self createStart];
//}

- (void)createAnimation
{
    [NSTimer scheduledTimerWithTimeInterval:4.0f target:self selector:@selector(createVC) userInfo:nil repeats:NO];
    self.label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    _label1.tag = 1;
    _label1.text = @"Welcome";
    NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 / 20.0 target:self selector:@selector(changeLabelColor) userInfo:nil repeats:YES];
    [time fire];
    _label1.numberOfLines = 0;
    _label1.textAlignment = NSTextAlignmentCenter;
    _label1.font = [UIFont systemFontOfSize:60];
    [self.view addSubview:_label1];
    [UIView animateWithDuration:3.0f delay:0 options: UIViewAnimationOptionBeginFromCurrentState animations:^{
        _label1.frame = self.view.frame;
    } completion:^(BOOL finished) {
        
    }];
    [_label1 release];
}
- (void)changeLabelColor
{
    static BOOL value = NO;
    if (!value) {
        value = YES;
        time(NULL);
    }
    float red = arc4random() % 256;
    float green = arc4random() % 256;
    float blue = arc4random() % 256;
    [_label1 setTextColor:[UIColor colorWithRed:red / 255.0f green:green / 255.0f blue:blue / 255.0f alpha:1]];
}
// 创建视图
- (void)createVC
{
    NSArray *array = [NSArray arrayWithObjects:@"头条", @"超极本", @"MID", @"新品", @"iPhone", @"DIY", nil];
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    scroll.showsHorizontalScrollIndicator = NO;
    scroll.backgroundColor = [UIColor whiteColor];
    
    for (int i = 0; i < [array count]; i++) {
        self.button = [UIButton buttonWithType:UIButtonTypeSystem];
        _button.frame = CGRectMake(self.view.frame.size.width / 6 * i, 0, self.view.frame.size.width / 6, scroll.frame.size.height);
        [_button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];
        [_button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [self.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_buttonArray addObject:_button];
        [scroll addSubview:_button];
    }
    self.button = [self.buttonArray objectAtIndex:0];
//    [self.button setBackgroundColor:[UIColor whiteColor]];
    [self.button.layer setCornerRadius:10.0];
    [self.view addSubview:scroll];
    [_button release];
    [scroll release];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 113 - 40);
    [flow setMinimumLineSpacing:0]; // 列距为零
    // 左右滑动
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, scroll.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - 113 - scroll.frame.size.height) collectionViewLayout:flow];
    self.collection.pagingEnabled = YES;
    self.collection.showsHorizontalScrollIndicator = NO;
    _collection.bounces = NO;
    [_collection setBackgroundColor:[UIColor whiteColor]];
    // 注册cell
    [self.collection registerClass:[NewsCollectionViewCell class] forCellWithReuseIdentifier:@"1"];
    [self.collection registerClass:[OneItemCollectionViewCell class] forCellWithReuseIdentifier:@"2"];
    self.collection.dataSource = self;
    self.collection.delegate = self;
    
    [self.view addSubview:self.collection];
    [flow release];
    [_collection release];
}
// button点击事件
- (void)buttonAction:(UIButton *)button
{
    [self.collection setContentOffset:CGPointMake(button.frame.origin.x * 6, 0) animated:YES];
}

// 获取数据
- (void)createData
{
    NSArray *array = [NSArray arrayWithObjects:@"999", @"301", @"700", @"2", @"5", @"120", nil];
    NSString *value = @"http://mrobot.pconline.com.cn/v2/cms/channels/999";
    [ConnectModel getConnectWith:value paramaters:nil block:^(NSMutableData*data){
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:nil];
        NSArray *array = [dic objectForKey:@"articleList"];
        SortModel *sortModel = [[SortModel alloc] init];
        for (NSDictionary *myDic in array) {
            NewsModel *model = [[NewsModel alloc] init];
            model.state = 0;
            [model setValuesForKeysWithDictionary:myDic];
            [sortModel.sortArray addObject:model];
            [model release];
        }
        sortModel.modelId = 0;
        [self.collectionArray addObject:sortModel];
        [sortModel release];
        // header
        NSArray *arrayHeader = [dic objectForKey:@"focus"];
        [self.headerArray addObjectsFromArray:arrayHeader];
    }];
    
    for (int i = 0; i < 6; i++) {
        if (i == 0) {
            continue;
        }
        NSString *value1 = [NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v2/cms/channels/%@", [array objectAtIndex:i]];
        [ConnectModel getConnectWith:value1 paramaters:nil block:^(NSMutableData*data){
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:nil];
            NSArray *array = [dic objectForKey:@"articleList"];
            SortModel *sortModel = [[SortModel alloc] init];
            for (NSDictionary *myDic in array) {
                NewsModel *model = [[NewsModel alloc] init];
                model.state = i;
                [model setValuesForKeysWithDictionary:myDic];
                [sortModel.sortArray addObject:model];
                [model release];
            }
            sortModel.modelId = i;
            [self.collectionArray addObject:sortModel];
            [sortModel release];
            [self.collection reloadData];
        }];
    }
}


//  排序
- (NSMutableArray *)sortUseBlock:(NSArray *)array
{
    NSMutableArray *myArray = [NSMutableArray arrayWithArray:array];
    [myArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        SortModel *first = (SortModel *)obj1;
        SortModel *second = (SortModel *)obj2;
        if (first.modelId > second.modelId) {
            return NSOrderedDescending;
        }
        else if (first.modelId == second.modelId)
        {
            return NSOrderedSame;
        }
        else
        {
            return NSOrderedAscending;
        }
    }];
    return myArray;
}

// 返回item的数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSMutableArray *array = [NSMutableArray array];
    array = [self sortUseBlock:self.collectionArray];
    [self.collectionArray removeAllObjects];
    [self.collectionArray addObjectsFromArray:array];
    return [self.collectionArray count];
}
// 给cell赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SortModel *model = [self.collectionArray objectAtIndex:indexPath.item];
    if (indexPath.item == 0 && model.modelId == 0) {
        OneItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"2" forIndexPath:indexPath];
        cell.delegate = self;
        [cell.itemArray removeAllObjects];
        [cell.itemArray addObjectsFromArray:model.sortArray];
        [cell.headerArray removeAllObjects];
        [cell.headerArray addObjectsFromArray:self.headerArray];
        return cell;
    } else {
        NewsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"1" forIndexPath:indexPath];
        cell.delegate = self;
        cell.numberModel = model;
        [cell.tableArray removeAllObjects];
        [cell.tableArray addObjectsFromArray:model.sortArray];
        [cell.tableView reloadData];
        return cell;
    }
}

// 点击button使视图做相应的调整
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    for (int i = 0; i < 6; i++) {
        if (i == self.collection.contentOffset.x / self.view.frame.size.width) {
            self.button = [self.buttonArray objectAtIndex:i];
            [self.button setBackgroundColor:[UIColor whiteColor]];
            [_button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [self.button.layer setCornerRadius:10.0];
        } else {
            self.button = [self.buttonArray objectAtIndex:i];
             [_button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            
        }
    }
}
// 点击视图使button做相应的调整
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    for (int i = 0; i < 6; i++) {
        if (i == scrollView.contentOffset.x / self.view.frame.size.width) {
            self.button = [self.buttonArray objectAtIndex:scrollView.contentOffset.x / self.view.frame.size.width];
             [_button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [self.button setBackgroundColor:[UIColor whiteColor]];
            [self.button.layer setCornerRadius:10.0];
        } else {
            self.button = [self.buttonArray objectAtIndex:i];
             [_button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}
// 点击进入详情
- (void)jionTheNext:(NSString *)url
{
    DetailViewController *news = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:news animated:YES];
    news.url = url;
    [news release];
}
- (void)jionNewsDetail:(NSString *)url
{
    DetailViewController *news = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:news animated:YES];
    news.url = url;
    [news release];
}
- (void)jionHeaderDetail:(NSString *)url
{
    HeaderViewController *header = [[HeaderViewController alloc] init];
    [self.navigationController pushViewController:header animated:YES];
    header.headerUrl = url;
    [header release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
